package loginfo

import (
	fc "MoSkeleton/framework/core/consts"
	"MoSkeleton/framework/core/dto/response"
	"MoSkeleton/framework/mo_gin"
	"MoSkeleton/framework/mo_gin/middleware"
	"MoSkeleton/framework/utils"
	"MoSkeleton/services"
	"MoSkeleton/web/pogos/request/monitor"
	"MoSkeleton/web/pogos/request/public"
	"bytes"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"io"
	"net/http"
	"net/url"
	"strings"
)

// 登录日志
func DoLogLoginInfo() gin.HandlerFunc {
	return func(c *gin.Context) {
		loginReq := public.LoginReq{}
		if err := c.ShouldBindJSON(&loginReq); err != nil {
			response.ValidatorError(c, err)
			return
		}
		c.Set(fc.GinContext_Model_Key, loginReq)
		c.Next()
		services.ServiceGroupInst.SystemGroupInst.SysLoginInfoServiceInst.AddLoginInfo(c, &loginReq)
	}
}

// 操作日志
func DoLogOperInfo() gin.HandlerFunc {
	return func(c *gin.Context) {
		monitor.NewOperLog4GinReq(c)
		body := readRequestBody(c)
		writer := middleware.ResponseBodyWriter{
			ResponseWriter: c.Writer,
			Body:           &bytes.Buffer{},
		}
		c.Writer = writer
		c.Next()
		services.ServiceGroupInst.SystemGroupInst.SysOperLogServiceInst.AddOperLog(c, body, &writer)
	}
}

func readRequestBody(c *gin.Context) *[]byte {
	var body []byte
	if utils.IsFileReuqest(c) {
		body = []byte("[文件]")
		return &body
	}
	if c.Request.Method != http.MethodGet {
		var err error
		body, err = io.ReadAll(c.Request.Body)
		if err != nil {
			mo_gin.MoLogger.Error("read body from request error:", zap.Error(err))
		} else {
			c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
		}
	} else {
		query := c.Request.URL.RawQuery
		query, _ = url.QueryUnescape(query)
		split := strings.Split(query, "&")
		m := make(map[string]string)
		for _, v := range split {
			kv := strings.Split(v, "=")
			if len(kv) == 2 {
				m[kv[0]] = kv[1]
			}
		}
		body, _ = json.Marshal(&m)
	}
	return &body
}
